<?php
/**
 * Created by PhpStorm.
 * User: kery
 * Date: 2017/4/10
 * Time: 18:31
 */
if(!function_exists('callApiServer')){
    function callApiServer($service ,$params=[], $is_async=false)
    {
        require_once 'RpcClient.php';
        $address_array = array(
            env('SERVICE_ERP_HOST')
        );

        $index = strripos($service, '.');
        $clazz = substr($service, 0, $index);
        $clazz = str_replace(".", '\\', $clazz);
        $method = substr($service, $index+1);
        $user = session('userinfo');
        if(!empty($user) && !isset($params['curr_user_id'])){
            $params['curr_user_id'] = $user['id'];
        }

        // 配置服务端列表
        RpcClient::config($address_array);
        $_client = RpcClient::instance($clazz);
        if(!$is_async){
            return $_client->$method($params);
        }

        $asend_method = 'asend_'.$method;
        $arecv_method = 'arecv_'.$method;

        $_client->$asend_method($params);

        // 异步接收数据
        $async_rs = $_client->$arecv_method($params);
        return $async_rs;
    }
}

if(!function_exists('str_format')){
    /**
     * 字符串格式化替换
     * format("My name is {1}, {0}", "Tommy", "Montgomery")
     * @param $format
     * @return mixed
     */
    function str_format() {
        $args = func_get_args();

        if (count($args) == 0) { return;}

        if (count($args) == 1) { return $args[0]; }

        $str = array_shift($args);

        $str = preg_replace_callback('/\\{(0|[1-9]\\d*)\\}/', create_function('$match', '$args = '.var_export($args, true).'; return isset($args[$match[1]]) ? $args[$match[1]] : $match[0];'), $str);

        return $str;
    }
}
